package com.zhenyi.limian.core;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.cjw.model.DBMap;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.utils.WexinPayUtils;
import com.wxpay.utils.Sha1Util;
import com.wxpay.utils.XmlUtil;

public class LMInterceptro implements Interceptor {
	protected final String APP_ID = PropKit.get("LM_APP_ID");
	protected final String HOST = PropKit.get("LM_HOST");

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();

		try {
			ApiConfigKit.setThreadLocalAppId(APP_ID);
			controller.setAttr("domain", HOST);
			inv.invoke();
		} catch (Exception e) {
			LogKit.warn("Fail to open wechat", e);
			controller.redirect(HOST);
			return;
		}
		try {
			String url = inv.getController().getRequest().getRequestURL().toString();
			String queryurl = inv.getController().getRequest().getQueryString();
			if (StrKit.notBlank(queryurl)) {
				url = url + "?" + queryurl;
			}
			Cache cache = Redis.use();
			String key = "ticket" + APP_ID;
			String ticket = cache.get(key);
			if (StrKit.isBlank(ticket)) {
				JsTicket jsTicket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
				ticket = jsTicket.getTicket();
				cache.setex(key, 7000, ticket);
			}
			DBMap info = signJS(url, APP_ID, ticket);
			controller.setAttr("sign", info);
		} catch (Exception e) {
			LogKit.warn("sign error");
		}
	}

	private DBMap signJS(String url, String appId, String jsapi_ticket) {
		String noncestr = WexinPayUtils.getNonceStr();
		String timestamp = Sha1Util.getTimeStamp();

		Map<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("noncestr", noncestr);
		packageParams.put("jsapi_ticket", jsapi_ticket);
		packageParams.put("timestamp", timestamp);
		packageParams.put("url", url);

		StringBuffer sb = new StringBuffer();
		Set<?> es = packageParams.entrySet();
		Iterator<?> it = es.iterator();
		while (it.hasNext()) {
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			if (k.endsWith(XmlUtil.FLAG_DATA)) {
				k = k.replace(XmlUtil.FLAG_DATA, "");
			}
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		String sign = sb.substring(0, sb.length() - 1);
		String signature = Sha1Util.getSha1(sign);
		DBMap map = new DBMap();
		map.put("noncestr", noncestr);
		map.put("appId", appId);
		map.put("timestamp", timestamp);
		map.put("signature", signature);
		map.put("url", url);
		map.put("jsapi_ticket", jsapi_ticket);
		return map;
	}
}
